import Vue from "vue";
import Router from "vue-router";
import store from "../store";

//封装一个函数用来控制局部权限
function hasUrl(url) {
  return store.getters.getUserInfo.menus_url.some(item => item == url);
}

Vue.use(Router);
//看看
export const indexRoutes = [
  {
    path: "/menu",
    component: () => import("@/views/menu/menu"),
    name: "菜单管理",
    beforeEnter(to, from, next) {
      hasUrl("/menu") ? next() : next("/home");
    }
  },
  {
    path: "/role",
    component: () => import("@/views/roler/roler"),
    name: "角色管理",
    beforeEnter(to, from, next) {
      hasUrl("/role") ? next() : next("/home");
    }
  },
  {
    path: "/manger",
    component: () => import("@/views/manger/manger"),
    name: "管理员管理",
    beforeEnter(to, from, next) {
      hasUrl("/manger") ? next() : next("/home");
    }
  },
  {
    path: "/category",
    component: () => import("@/views/category/category"),
    name: "商品分类",
    beforeEnter(to, from, next) {
      hasUrl("/category") ? next() : next("/home");
    }
  },
  {
    path: "/specs",
    component: () => import("@/views/specs/specs"),
    name: "商品规格",
    beforeEnter(to, from, next) {
      hasUrl("/specs") ? next() : next("/home");
    }
  },
  {
    path: "/goods",
    component: () => import("@/views/goods/goods"),
    name: "商品管理",
    beforeEnter(to, from, next) {
      hasUrl("/goods") ? next() : next("/home");
    }
  },
  {
    path: "/banner",
    component: () => import("@/views/banner/banner"),
    name: "轮播图管理",
    beforeEnter(to, from, next) {
      hasUrl("/banner") ? next() : next("/home");
    }
  },
  {
    path: "/member",
    component: () => import("@/views/member/member"),
    name: "会员管理",
    beforeEnter(to, from, next) {
      hasUrl("/member") ? next() : next("/home");
    }
  },
  {
    path: "/seckill",
    component: () => import("@/views/seckill/seckill"),
    name: "秒杀管理",
    beforeEnter(to, from, next) {
      hasUrl("/seckill") ? next() : next("/home");
    }
  }
];

let router = new Router({
  routes: [
    {
      path: "/login",
      component: () => import("@/pages/login")
    },
    {
      path: "/index",
      component: () => import("@/pages/index"),
      children: [
        {
          path: "/home",
          component: () => import("@/views/home")
        },
        ...indexRoutes,
        {
          path: "",
          redirect: "/home"
        }
      ]
    },
    {
      path: "*",
      redirect: "/login"
    }
  ]
});

//全局导航守卫之登录拦截
router.beforeEach((to, from, next) => {
  if (to.path == "/login") {
    next();
    return;
  }
  console.log(store.getters, "store.gettersstore.getters");
  if (store.getters.getUserInfo) {
    next();
    return;
  }
  next("/login");
});

export default router;
